<template>
  <div class="post-container">
    <el-form ref="editFormRef" :model="editData" :rules="menuFormRules" label-width="100px">
      <el-form-item label="文章名称" prop="title">
        <el-input v-model="editData.title" placeholder="请输入文章名称" />
      </el-form-item>
      <el-form-item label="文章封面图" prop="imgUrl">
        <el-upload
          :headers="header"
          :action="action"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
        >
          <img v-if="editData.imgUrl" :src="editData.imgUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章标签" prop="tagIds">
        <el-select multiple v-model="editData.tagIds" placeholder="请选择文章标签">
          <template v-for="item in tagList" :key="item.id">
            <el-option :label="item.name" :value="item.id"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="文章分类" prop="categoryId">
        <el-select v-model="editData.categoryId" placeholder="请选择文章分类">
          <template v-for="item in cateGoryList" :key="item.id">
            <el-option :label="item.name" :value="item.id"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <WangEditor @getWangEditorValue="getWangEditorValue" :content="editData.content"></WangEditor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitMenuForm" :loading="loading">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
import { CategoryAllList } from '@/api/category'
import { TagAllList } from '@/api/tag'
import { PostAddData } from '@/api/post'
import { ElForm } from 'element-plus'
import { defineComponent, getCurrentInstance, PropType, ref, watchEffect } from 'vue'
import WangEditor from '@/components/WangEditor/index.vue'
import { getToken } from '@/utils/auth'

type FormInstance = InstanceType<typeof ElForm>

export default defineComponent({
  name: 'EditTag',
  components: {
    WangEditor
  },
  props: {
    type: {
      type: Number,
      required: true
    },
    data: {
      type: Object as PropType<PostAddData>
    },
    cateGoryList: {
      type: Array as PropType<CategoryAllList[]>,
      required: true
    },
    tagList: {
      type: Array as PropType<TagAllList[]>,
      required: true
    }
  },
  emit: ['submit'],
  setup(props, { emit }) {
    const loading = ref(false)
    const action = ref(`${process.env.VUE_APP_BASE_API}/post/upload`)
    const header = ref({ token: getToken() })
    const { proxy } = getCurrentInstance()!
    const editFormRef = ref<FormInstance | null>(null)
    const editData = ref({
      title: '',
      content: '',
      categoryId: '',
      imgUrl: '',
      tagIds: [] as number[]
    })
    const getWangEditorValue = (str: string) => {
      const obj = { content: str }
      editData.value = { ...editData.value, ...obj }
    }
    const defultProps = {
      title: '',
      content: '',
      categoryId: '',
      imgUrl: '',
      tagIds: [] as number[]
    }
    watchEffect(() => {
      if (props.data) {
        // 移除之前表单效验结果
        editFormRef.value?.clearValidate()
        editData.value = { ...defultProps, ...props.data }
      }
    })
    // 验证规则
    const menuFormRules = {
      title: [{
        required: true,
        message: '请输入文章标标题',
        trigger: 'blur'
      }],
      content: [{
        required: true,
        message: '请输入内容',
        trigger: 'blur'
      }],
      categoryId: [{
        required: true,
        message: '请选择分类',
        trigger: 'blur'
      }],
      tagIds: [{
        required: true,
        message: '请选择标签',
        trigger: 'blur'
      }],
      imgUrl: [{
        required: true,
        message: '请上传文章封面图',
        trigger: 'change'
      }]

    }
    // 上传文件之前
    const beforeAvatarUpload = (file: any) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        proxy?.$message.error('上传文件格式为 jpeg｜jpg')
      }
      if (!isLt2M) {
        proxy?.$message.error('封面图不得大于2M')
      }
      return isJPG && isLt2M
    }
    // 上传文件成功之后
    const handleAvatarSuccess = (res: any, file: any) => {
      console.log(file.response)
      editData.value.imgUrl = `https://${file.response.data.res.Location}`
    }
    // 提交
    const submitMenuForm = () => {
      (editFormRef.value as FormInstance).validate(valid => {
        if (valid) {
          emit('submit', editData.value)
        }
      })
    }
    return {
      loading,
      menuFormRules,
      editFormRef,
      editData,
      action,
      header,
      submitMenuForm,
      getWangEditorValue,
      beforeAvatarUpload,
      handleAvatarSuccess
    }
  }
})
</script>
<style lang="scss" scoped>
.post-container {
  padding: 20px;
}
</style>
<style lang="scss">
.post-container {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    height: 178px;
    width: 178px;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
